package com.crane.common.framework.shiro;


import com.crane.common.core.dto.SessUser;
import com.crane.common.core.exception.BizException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;


/**
 * 认证
 *
 * @author zhenxing.pi
 */
public abstract class AbstractUserRealm extends AuthorizingRealm {


    private static final Logger logger = LoggerFactory.getLogger(AbstractUserRealm.class);

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //用户权限列表
        Set<String> permsSet = null;
        //业务逻辑  获取权限
        try {
            permsSet = getStringPermissions(principals);
        } catch (BizException e) {
            logger.error(e.getMessage());
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        SessUser user = null;
        try {
            user = getSessUser(token);
        } catch (BizException e) {
            throw new AuthenticationException(e.getMessage());
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, token.getCredentials(), getName());
        return info;
    }


    @Override
    protected Object getAuthorizationCacheKey(PrincipalCollection principals) {
        SessUser user = (SessUser) principals.getPrimaryPrincipal();
        return user.getUserName() + ":authorization";
    }

    protected abstract Set<String> getStringPermissions(PrincipalCollection principals) throws BizException;


    protected abstract SessUser getSessUser(AuthenticationToken token) throws BizException;


}
